package main

import (
	"fmt"
	"net/http"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	lumberjack "gopkg.in/natefinch/lumberjack.v2"
)

var (
	alevel = zap.NewAtomicLevel()
)

func main() {
	http.HandleFunc("/handle/level", alevel.ServeHTTP)
	go func() {
		if err := http.ListenAndServe(":9090", nil); err != nil {
			panic(err)
		}
	}()
	// 默认是Info级别
	logger := initLogger("./logs/all.log", "info") //logcfg.Build()
	defer logger.Sync()
	i := 0
	for i = 0; i < 9*1000*1000; i++ {
		//time.Sleep(1 * time.Second)
		logger.Debug("debug log", zap.String("level", alevel.String()), zap.Int("cnt", i), zap.Int64("ts", time.Now().Local().Unix()))
		logger.Info("info log", zap.String("level", alevel.String()), zap.Int("cnt", i), zap.Int64("ts", time.Now().Local().Unix()))
	}

	logger.Warn("warn log", zap.String("level", alevel.String()), zap.Int("cnt", i), zap.Int64("ts", time.Now().Local().Unix()))
	fmt.Printf("log complete[i: %d].\n", i)

	time.Sleep(time.Second * 5)
}

func initLogger(logpath string, loglevel string) *zap.Logger {
	hook := lumberjack.Logger{
		Filename:   logpath, // ⽇志⽂件路径
		MaxSize:    1,       // megabytes
		MaxBackups: 30,      // 最多保留n个备份
		MaxAge:     30,      //days
		LocalTime:  true,
		Compress:   true, // 是否压缩 disabled by default
	}
	w := zapcore.AddSync(&hook)
	switch loglevel {
	case "debug":
		alevel.SetLevel(zap.DebugLevel)
	case "info":
		alevel.SetLevel(zap.InfoLevel)
	case "error":
		alevel.SetLevel(zap.ErrorLevel)
	default:
		alevel.SetLevel(zap.InfoLevel)
	}
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		w,
		alevel,
	)
	logger := zap.New(core)
	logger.Info("DefaultLogger init success")
	return logger
}
